<?php
namespace app\admin\controller;

use app\common\controller\Base;
use app\common\service\User as UserService;
use app\common\service\UserRole as UserRoleService;
use think\Request;

class User extends Base{

    /**
     * 用户列表
     */
    public function index(){

        $userService = new UserService();
        $users = $userService->getUsers();

        return view('',['users'=>$users]);
    }

    public function add(){

        //用户可以选择的角色
        $userRoleService = new UserRoleService();
        $roles = $userRoleService ->getRoles();

        return view('',['roles'=>$roles]);
    }


    public function create(Request $request){

        if(!$request->isPost()){
            $this->error("非法途径访问");
        }
        $data = $request->only(['name','nickname','account','password','avatar','role_id']);

        $userService = new UserService();
        $result = $userService ->insert($data);

        if($result['state']) {
            $this->success("操作成功");
        }else{
            $this->error($result['message']);
        }

    }

    public function edit(Request $request){

        $input = $request->only(['id']);

        $id = intval($input['id']);

        $userService = new UserService();
        $user = $userService ->getUser($id);

        $userRoleService = new UserRoleService();
        $roles = $userRoleService ->getRoles();

        return view('',['roles'=>$roles,'user'=>$user]);
    }


    public function update(Request $request){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }

        $data = $request->only(['id','name','nickname','account','password','avatar','role_id']);

        $userService = new UserService();
        $result = $userService ->update($data);

        if(1 == $result['state']) {
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }

    public function delete(Request $request){
        if(!$request->isDelete()){
            $this->error("非法访问途径");
        }

        $id = $request->only(['id']);
        if(count($id) !== 1){
            $this->error("禁止批量操作");
        }

        $userService = new UserService();

        $count = $userService -> delete($id);

        if($count){
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }


}






























